<template>
  <view>
    <z-paging ref="paging" v-model="data.orderList" @query="getOrderList" refresher-enabled>
      <template #top>
        <view class="search-time flex items-center bg-white py-2 px-2 box-border">
          <view class="time-flex1 text-align-left">选择日期</view>
          <view class="time-flex2 flex items-center bg-gray-1 c-br text-align-center">
            <view
              class="px-2 py-2 flex-1 border-box c-blueGray c-text-12"
              @click="
                () => {
                  data.timeShow = true;
                  data.timeSelect = 1;
                }
              "
              >{{ data.beginDate ? data.beginDate : '开始日期' }}</view
            >
            <view class="px-2 py-2 flex-0 border-box c-blueGray c-text-12"> — </view>
            <view
              class="px-2 py-2 flex-1 border-box c-blueGray c-text-12"
              @click="
                () => {
                  data.timeShow = true;
                  data.timeSelect = 2;
                }
              "
              >{{ data.endDate ? data.endDate : '结束日期' }}</view
            >
          </view>
          <view class="time-flex3 text-align-right">
            <van-button type="primary" size="small" @click="onSearch">查询</van-button>
          </view>
        </view>
      </template>
      <view class="list c-pd">
        <view v-for="(item, index) in data.orderList" :key="index">
          <OrderListCard :order-info="item" :is-btn="false"></OrderListCard>
        </view>
      </view>
      <template #bottom>
        <view class="px-3 box-border">
          <van-button class="px-2 py-2 box-border" color="#ffc300" @click="exportOrder" block>导出</van-button>
        </view>
      </template>
    </z-paging>
    <van-popup position="bottom" custom-style="height: 40%;" :show="data.timeShow">
      <van-datetime-picker title="选择日期" @cancel="onClose" type="date" :value="data.currentDate" @confirm="onConfirm" />
    </van-popup>
  </view>
</template>

<script setup lang="ts">
import OrderRequest from '@/request/orderRequest';
import { onLoad } from '@dcloudio/uni-app';
import Tools from '@/utils/tools';
import useModal from '@/hooks/useModal';
import useToast from '@/hooks/useToast';
import useAppStore from '@/store/modules/app';

const { showModal } = useModal();
const { showToast } = useToast();
const store = useAppStore();

interface IData {
  pages: {
    pageNo: number;
    pageSize: number;
    totalPage: number;
  };
  beeperId?: number;
  beginDate: string;
  endDate: string;
  timeShow: boolean;
  orderList: IOrderList[];
  minDate: number;
  maxDate: number;
  currentDate: string;
  timeSelect: number;
}

const data = reactive<IData>({
  timeShow: false,
  pages: {
    pageNo: 1,
    pageSize: 10,
    totalPage: 1,
  },
  beginDate: '',
  endDate: '',
  orderList: [],
  beeperId: store.$state.beeperId,
  minDate: new Date(2020, 0, 1).getTime(),
  maxDate: new Date(2026, 0, 31).getTime(),
  currentDate: '',
  timeSelect: 1,
});

const paging = ref();

onLoad(() => {
  getCurrentDate();
});

const getOrderList = (pageNo: number, pageSize: number) => {
  const params = {
    pageNo,
    pageSize,
    beeperId: data.beeperId,
    beginDate: data.beginDate,
    endDate: data.endDate,
    hasLoading: true,
  };
  // 此处请求仅为演示，请替换为自己项目中的请求
  OrderRequest.GetOrderList(params)
    .then((res) => {
      // 将请求结果通过complete传给z-paging处理，同时也代表请求结束，这一行必须调用
      paging.value.complete(res.data.list);
    })
    .catch((err) => {
      paging.value.complete(false);
    });
};

const onClose = () => {
  data.timeShow = false;
};

const onSearch = () => {
  paging.value!.reload();
};

const getCurrentDate = () => {
  const { year, month, day } = Tools.formatTimestampToDate(Number(new Date()));
  data.beginDate = year + '-' + month + '-' + day;
  data.endDate = year + '-' + month + '-' + day;
};

const exportOrder = () => {
  const { beeperId, beginDate, endDate } = data;

  showModal('确定导出？', {
    showCancel: true,
    success: (resM) => {
      if (resM.confirm) {
        const params = {
          beeperId,
          beginDate: beginDate + ' 00:00:00',
          endDate: endDate + ' 23:59:59',
          hasLoading: true,
        };
        //
        OrderRequest.GetOrderExportUrl(params).then((res) => {
          if (res.status === 0) {
            uni.downloadFile({
              // 示例 url，并非真实存在
              url: res.data,
              success: function (res) {
                uni.openDocument({
                  showMenu: true,
                  filePath: res.tempFilePath,
                });
              },
            });
            showToast('导出成功', 'success');
          }
        });
      }
    },
  });
};

const onConfirm = (event: any) => {
  const { year, month, day } = Tools.formatTimestampToDate(event.detail);
  if (data.timeSelect === 1) {
    data.beginDate = year + '-' + month + '-' + day;
  } else {
    data.endDate = year + '-' + month + '-' + day;
  }
  onClose();
};
</script>

<style lang="scss" scoped>
.time-flex1 {
  flex: 1;
}

.time-flex2 {
  flex: 3;
}

.time-flex3 {
  flex: 1;
}
</style>
